package utils

import (
	"encoding/json"
	"net/http"
)

// 响应的基本信息
type H struct {
	Code int         `json:"code" `
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

type HLIST struct {
	Code  int `json:"code" `
	Total int `json:"Total"`
	Data  any `json:"data"`
}

// 响应成功的公用方法
func Resp(w http.ResponseWriter, code int, data interface{}, msg string) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	h := H{
		Code: code,
		Msg:  msg,
		Data: data,
	}
	ret, err := json.Marshal(h)
	if err != nil {
		panic("json格式转换错误")
	}
	w.Write(ret)
}

// 响应成功的公用方法
func RespList(w http.ResponseWriter, code int, data any, total int) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	h := HLIST{
		Code:  code,
		Total: total,
		Data:  data,
	}
	ret, err := json.Marshal(h)
	if err != nil {
		panic("json格式转换错误")
	}
	w.Write(ret)
}

// 失败的响应
func RespFail(w http.ResponseWriter, msg string) {
	Resp(w, -1, nil, msg)
}

// 成功的响应
func RespOk(w http.ResponseWriter, data interface{}) {
	Resp(w, 210, data, "")
}

// 成功的响应
func RespOkList(w http.ResponseWriter, data any, total int) {
	RespList(w, 210, data, total)
}
